<?php

namespace App\Models;
use stdClass;

class UserModel extends BaseModel {

	public function __construct() {
		parent::__construct();
		$this -> _table = "user";
	}

	public function Img($username, $data) {
		//		$table = $this -> _table;
		$sql = sprintf("update `%s` set %s where `UserName` = '%s'", $this -> _table, $this -> formatUpdate($data), $username);
		$sth = $this -> _dbHandle -> prepare($sql);
		$sth -> execute();
		$result = $sth -> fetchAll();
		return $result;
	}

	public function getUserInfo($username, $password) {
//		$table = $this -> _table;
		//		$sql = "select * from $table where UserName = '" . $username . "' and PassWord = '" . $password . "'";
		//		return $this -> query($sql);
		$sql = sprintf("select * from `%s` where UserName = '%s' and PassWord = '%s'", $this -> _table, $username, $password);
		$sth = $this -> _dbHandle -> prepare($sql);
		$sth -> execute();
		return $sth -> fetchAll();
	}

	public function getUserRolePower($user, $urlpath) {
		$sql = "SELECT UserName FROM `user` INNER JOIN role ON `user`.RoleId=role.ID INNER JOIN rolepower ON role.ID=rolepower.RoleId INNER JOIN power ON power.ID=rolepower.PowerId WHERE UserName='" . $user . "' AND power.ControllerAction='" . $urlpath . "'";
		//	 	$sql = "select ControllerAction FROM user INNER JOIN rolepower on 'user'.RoleId = rolepower.RoleId INNER JOIN power on rolepower.PowerId = power.Id WHERE UserName= '" . $user . "' and ControllerAction='" . $urlpath . "'";
		return $this -> query($sql);
	}

	public function getDate() {
		//获取Datatables发送的参数 必要
		$draw = $_GET['draw'];
		//这个值作者会直接返回给前台

		//排序
		$order_column = $_GET['order']['0']['column'];
		//那一列排序，从0开始
		$order_dir = $_GET['order']['0']['dir'];
		//ase desc 升序或者降序

		//拼接排序sql
		$orderSql = "";
		if (isset($order_column)) {
			$i = intval($order_column);
			switch($i) {
				case 0 :
					$orderSql = " order by id " . $order_dir;
					break;
				case 1 :
					$orderSql = " order by username " . $order_dir;
					break;
				case 2 :
					$orderSql = " order by nickname " . $order_dir;
					break;
				case 3 :
					$orderSql = " order by roleid " . $order_dir;
					break;
				case 4 :
					$orderSql = " order by email" . $order_dir;
					break;
				case 5 :
					$orderSql = " order by sex" . $order_dir;
					break;
				case 6 :
					$orderSql = " order by age " . $order_dir;
					break;
				case 7 :
					$orderSql = " order by phone " . $order_dir;
					break;
				case 8 :
					$orderSql = " order by address " . $order_dir;
					break;
				default :
					$orderSql = '';
			}
		}
		//搜索
		$search = $_GET['search']['value'];
		//获取前台传过来的过滤条件
		//分页
		$start = $_GET['start'];
		//从多少开始
		$length = $_GET['length'];
		//数据长度
		$limitSql = '';
		$limitFlag = isset($_GET['start']) && $length != -1;
		if ($limitFlag) {
			$limitSql = " LIMIT " . intval($start) . ", " . intval($length);
		}
		//
		//定义查询数据总记录数sql
		$sumSql = sprintf("select count(id) as sum FROM user");

		//		$sumSql = "SELECT count(id) as sum FROM user";
		//条件过滤后记录数 必要
		$recordsFiltered = 0;
		//表的总记录数 必要
		$recordsTotal = 0;
		$recordsTotalResult = $this -> _dbHandle -> prepare($sumSql);
		$recordsTotalResult -> execute();

		while ($row = $recordsTotalResult -> fetchAll()) {
			$recordsTotal = $row['0']['sum'];
		}
		//定义过滤条件查询过滤后的记录数sql
		$sumSqlWhere = " where ID||UserName||Email||RoleId||NickName||sex||Phone||age||address '%" . $search . "%'";
		if (strlen($search) > 0) {
			$recordsFilteredResult = $this -> _dbHandle -> prepare($sumSql . $sumSqlWhere);
			while ($row = $recordsFilteredResult -> fetchAll()) {
				$recordsFiltered = $row['0']['sum'];
			}
		} else {
			$recordsFiltered = $recordsTotal;
		}
		//query data
		$totalResultSql = sprintf("SELECT ID,UserName,Email,RoleId,NickName,sex,Phone,age,address FROM user");
		$arr = array();
		//直接查询所有记录
		$dataResult = $this -> _dbHandle -> prepare($totalResultSql . $orderSql . $limitSql);
		$dataResult -> execute();
		while ($row = $dataResult -> fetchAll()) {
			for ($i = 0, $index1 = $start + 1; $i < count($row); $i++, $index1++) {
				$row[$i]['ID'] = $index1;
			}
			for ($i = 0; $i < sizeof($row); $i++) {
				$obj = new stdClass();
				$obj -> id = $row[$i]['ID'];
				$obj -> username = $row[$i]['UserName'];
				$obj -> email = $row[$i]['Email'];
				$obj -> roleid = $row[$i]['RoleId'];
				$obj -> nickname = $row[$i]['NickName'];
				$obj -> sex = $row[$i]['sex'] == 0 ? "男" : "女";
				$obj -> phone = $row[$i]['Phone'];
				$obj -> age = $row[$i]['age'];
				$obj -> address = $row[$i]['address'];
				$arr[$i] = $obj;
			}
		}

		/*
		 * Output 包含的是必要的
		 */
		echo json_encode(array("draw" => intval($draw), "recordsTotal" => intval($recordsTotal), "recordsFiltered" => intval($recordsFiltered), "data" => $arr));

		function fatal($msg) {
			echo json_encode(array("error" => $msg));
			exit(0);
		}

	}

	public function getSelf($username) {
		$this -> filter = "where UserName='" . $username . "'";
		$info = $this -> selectAll();
		return json_encode($info);
	}

	public function userAdd($username, $email, $phone) {
		$table = $this -> _table;
		$sql1 = "select * from $table where UserName = '" . $username . "'";
		$sql2 = "select * from $table where Email = '" . $email . "'";
		$sql3 = "select * from $table where Phone = '" . $phone . "'";
		if ($this -> query($sql1)) {
			$data = array('message' => '该用户名已存在', 'code' => 101);
		} elseif ($this -> query($sql2)) {
			$data = array('message' => '该邮箱已存在', 'code' => 102);
		} elseif ($phone != '' && $this -> query($sql3)) {
			$data = array('message' => '该手机号已存在', 'code' => 103);
		} else {
			$data = array('message' => '成功', 'code' => 0);
		}
		return json_encode($data);
	}

	public function userupdata($username, $email, $nickname, $sex, $phone, $age, $address) {
		$table = $this -> _table;
		$sql1 = "select * from $table where Email = '" . $email . "'and UserName !='" . $username . "'";
		$sql2 = "select * from $table where Phone = '" . $phone . "' and UserName !='" . $username . "'";
		$sql3 = "update $table set Email = '" . $email . "', NickName = '" . $nickname . "', sex ='" . $sex . "', Phone ='" . $phone . "', age = " . $age . " , Address ='" . $address . "' where UserName ='" . $username . "'";

		if ($this -> query($sql1)) {
			$msg = array('message' => '该邮箱已存在', 'code' => 101);
		} elseif ($this -> query($sql2)) {
			$msg = array('message' => '该手机号已存在', 'code' => 102);
		} elseif ($this -> query($sql3)) {
			$msg = array('message' => '修改成功', 'code' => 0);
		} else {
			$msg = array('message' => '修改失败（原因：未修改信息）', 'code' => 2);
		}
		return json_encode($msg);
	}

	public function pswUpdate($username, $password, $password2) {
		$table = $this -> _table;
		$sql1 = "select * from $table where UserName ='" . $username . "'and PassWord ='" . $password . "'";
		$sql2 = "update $table set PassWord ='" . $password2 . "' where UserName ='" . $username . "'";
		if ($this -> query($sql1)) {
			if ($this -> query($sql2)) {
				$msg = array('message' => '密码修改成功', 'code' => 0);
			} else {
				$msg = array('message' => '新密码与旧密码相同', 'code' => 101);
			}
		} else {
			$msg = array('message' => '原密码输入有误', 'code' => 102);
		}
		return $msg;
	}

	public function pswSelect($username, $email, $phone) {
		$sql = sprintf("select * from %s where UserName = '%s' and Email = '%s' and Phone = '%s'", $this -> _table, $username, $email, $phone);
		$arr = array();
		//直接查询所有记录
		$result = $this -> _dbHandle -> prepare($sql);
		$result -> execute();
		if ($result -> rowCount()) {
			while ($row = $result -> fetchAll()) {
				for ($i = 0; $i < sizeof($row); $i++) {
					$obj = new stdClass();
					$obj -> psw = $row[$i]['PassWord'];
					$arr[$i] = $obj;
				}
			}
			$msg = array('message' => $arr[0] -> psw, 'code' => 0);
		} else {
			$msg = array('message' => '请输入正确个人信息，否则无法找回密码！', 'code' => 101);

		}
		return $msg;
	}

}
?>